<?php

class AdminController extends AbstractAdminController
{
	public function actionList($categoryId = null)
	{
        $oPages = new Pages();

        $oRowset = $oPages->getAll($this->oPager, $categoryId);

		$this->render('list', array(
            'oRowset' => $oRowset,
		    'categoryId' => $categoryId
        ));
	}

    public function actionEditor($categoryId = null)
    {
	    $toView = array();

        $oPages = new Pages();
        $oPhotos = new Photos();

        $id = $this->_getParam('id');

	    if($id > 0)
		    $oPages = $oPages->findByPk($id);

        if($this->_isPost())
        {
            $attr = $this->_getPost();

	        if(!$oPages || !$oPages->id)
	        {
		        $oPages = new Pages();

		        $attr['user_add'] = $this->_userInfo->id;
		        $attr['date_add'] = date('Y-m-d H:i:s');
	        }
	        else
	        {
		        $attr['user_edit'] = $this->_userInfo->id;
		        $attr['date_edit'] = date('Y-m-d H:i:s');
	        }

	        if(!empty($attr['title']))
	            $attr['alias'] = $oPages->generateAlias(($oPages && $oPages->id ? $oPages->id : null), $attr['title']);

//	        print_r($attr); exit;
	        $oPages->setAttributes($attr);

            if($oPages->save())
            {
                $oPhotos->saveByTarget($oPages, $this->_getPost());

                return $this->redirect(Yii::app()->createUrl('/admin/pages/list'));
            }
        }

	    if($oPages)
		    $oPhotos->selectAllByRow($oPages);

	    $toView['oRow'] = $oPages;
	    $toView['categoryId'] = $categoryId;

        $this->render('edit', $toView);
    }

    public function actionDelete($id = null)
    {
        $oPages = new Pages();
        $oPhoto = new Photos();
        $oFiles = new Files();

        $oPages = $oPages->findByPk($id);

        $oPhoto->selectByRow($oPages);

        if(!empty($oPages) && !empty($oPages['photos']))
        {
            foreach($oPages['photos'] as $oPhoto)
            {
                $oFiles->deleteDirectory(PUBLIC_PATH . $oPhoto->path);

                $oPhoto->delete();
            }
        }

        $oPages->delete();

        $returnUrl = Yii::app()->user->returnUrl;

        if(!empty($_SERVER['HTTP_REFERER']))
            $returnUrl = $_SERVER['HTTP_REFERER'];

        return $this->redirect($returnUrl);
    }

}